package com.xd.guessmusic.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.xd.guessmusic.R;
import com.xd.guessmusic.data.Const;
import com.xd.guessmusic.model.IAlertDialogButtonListener;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * 工具类
 * Created by DGF on 2015/5/14.
 */
public class Util {

    /**
     * 获取当前Activity的屏幕截屏
     * @param activity
     * @return
     */
    public static Bitmap getShot(Activity activity) {
        // 获取windows中最顶层的view
        View view = activity.getWindow().getDecorView();
        view.buildDrawingCache();

        // 获取状态栏高度
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        int statusBarHeights = rect.top;
        Display display = activity.getWindowManager().getDefaultDisplay();

        // 获取屏幕宽和高
        int widths = display.getWidth();
        int heights = display.getHeight();

        // 允许当前窗口保存缓存信息
        view.setDrawingCacheEnabled(true);

        // 去掉状态栏
        Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
                statusBarHeights, widths, heights - statusBarHeights);

        // 销毁缓存信息
        view.destroyDrawingCache();

        return bmp;
    }

    /**
     * 将bmp转换为字节数组
     * @param bmp
     * @param needRecycle
     * @return
     */
    public static byte[] bmpToByteArray(final Bitmap bmp, boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 读取游戏数据
     * @param context
     * @return
     */
    public static int[] loadData(Context context){
        FileInputStream fis = null;

        int[] result = {-1, Const.TOTAL_COINS};

        try {
            fis = context.openFileInput(Const.FILE_NAME_SAVE_DATA);

            DataInputStream dis = new DataInputStream(fis);

            result[Const.INDEX_LOAD_DATA_STAGE] = dis.readInt();
            result[Const.INDEX_LAOD_DATA_COINS] = dis.readInt();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

    /**
     * 游戏数据保存
     * @param context
     * @param stageIndex
     * @param coins
     */
    public static void saveData(Context context, int stageIndex, int coins){
        FileOutputStream fos = null;

        try {
            fos = context.openFileOutput(Const.FILE_NAME_SAVE_DATA, Context.MODE_PRIVATE);

            DataOutputStream dos = new DataOutputStream(fos);

            dos.writeInt(stageIndex);
            dos.writeInt(coins);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static AlertDialog alertDialog;

    /**
     * 显示自定义对话框
     * @param context
     * @param message
     * @param listener
     */
    public static void showDialog(final Context context,
                                  String message,
                                  final IAlertDialogButtonListener listener){
        View view = getView(context, R.layout.dialog_view);

        ImageButton btnCancel = (ImageButton)view.findViewById(R.id.btn_dialog_cancel);
        ImageButton btnOK = (ImageButton)view.findViewById(R.id.btn_dialog_ok);
        TextView txtMessage = (TextView)view.findViewById(R.id.txt_dialog_message);

        txtMessage.setText(message);

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭对话框
                if (alertDialog != null){
                    alertDialog.cancel();
                }
                MyPlayer.playSound(context, MyPlayer.INDEX_SOUND_CANCEL);
            }
        });

        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭对话框
                if (alertDialog != null){
                    alertDialog.cancel();
                }

                MyPlayer.playSound(context, MyPlayer.INDEX_SOUND_ENTER);

                //事件回调
                if (listener != null){
                    listener.onClick();
                }
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.Theme_Transparent);
        builder.setView(view);

        alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 界面跳转
     * @param context
     * @param dest
     */
    public static void startActivity(Context context, Class dest){
        Intent intent = new Intent();
        intent.setClass(context, dest);
        context.startActivity(intent);

        //关闭当前的Activity
        ((Activity)context).finish();
    }

    /**
     * 获取视图
     * @param context
     * @param layoutId
     * @return
     */
    public static View getView(Context context, int layoutId){
//        LayoutInflater inflater = LayoutInflater.from(context);
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return inflater.inflate(layoutId, null);
    }

    /**
     * 获取随机汉字
     * @return
     */
    public static char getRandomChar(){
        Random random = new Random();
        /**
         * 高位码：取39可获得较常用的汉字
         */
        int highPos = 176+random.nextInt(39);
        /**
         * 低位码：取93可获得较常用的汉字
         */
        int lowPos = 161+random.nextInt(93);

        /**
         * 转换为字节数组
         */
        byte[] bytes = new byte[2];
        bytes[0] = Integer.valueOf(highPos).byteValue();
        bytes[1] = Integer.valueOf(lowPos).byteValue();

        /**
         * 获取汉字
         */
        String str = "";
        try {
            str = new String(bytes, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return str.charAt(0);
    }
}
